package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmswms.entity.*;
import com.sunda.spmswms.mapper.SapDeliveryNoteMapper;
import com.sunda.spmswms.mapper.WithdrawTaskDtlMapper;
import com.sunda.spmswms.mapper.WithdrawTaskMapper;
import com.sunda.spmswms.service.IWithdrawTaskDtlService;
import com.sunda.spmswms.service.IWithdrawTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 移动冲销表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-04-25
 */
@Service
public class WithdrawTaskServiceImpl extends ServiceImpl<WithdrawTaskMapper, WithdrawTask> implements IWithdrawTaskService {

    @Autowired
    WithdrawTaskMapper withdrawTaskMapper;
    @Autowired
    WithdrawTaskDtlMapper withdrawTaskDtlMapper;

    @Autowired
    IWithdrawTaskDtlService iWithdrawTaskDtlService;

    @Autowired
    SapDeliveryNoteMapper sapDeliveryNoteMapper;

    /*
     * 根据条件获取单据列表，可支持的搜索条件有
     * deliveryNoteSap sapDN单号
     * datePeriod:['2021-04-01','2021-05-01'],
     * mobileType:'101'  采购入库
     * */
    @Override
    public ResponseResult getWithdrawableList(JSONObject jsonObject) {
        String deliveryNoteSap = jsonObject.getString("deliveryNoteSap");
        JSONArray datePeriod = jsonObject.getJSONArray("datePeriod");
        String mobileType = jsonObject.getString("mobileType");
        if (StringUtils.isEmpty(mobileType)) {
            return ResponseResult.error("mobileType is mandatory required");
        }

        String startDate = null;
        String endDate = null;

        if (null != datePeriod && datePeriod.size() == 2) {
            startDate = datePeriod.getString(0).replaceAll("-","");
            endDate = datePeriod.getString(1).replaceAll("-","");
        }

        switch (mobileType) {
            case "101":
                // 采购入库
                QueryWrapper queryWrapper = new QueryWrapper<SapDeliveryNote>().eq("MOBILE_TYPE", mobileType).isNotNull("SPMS_STATUS").gt("SPMS_STATUS","0");
                if (StringUtils.isNotEmpty(deliveryNoteSap)) {
                    queryWrapper.eq("DELIVERY_NOTE_SAP", deliveryNoteSap);
                }
                if (null != startDate && null != endDate) {
                    queryWrapper.between("DOCUMENT_DATE", startDate, endDate);
                }
                return ResponseResult.success().add("sapDeliveryNotes", sapDeliveryNoteMapper.selectList(queryWrapper));
            default:
                return ResponseResult.error("The mobileType is not validate, mobileType:" + mobileType);

        }
    }

    /* 生成入库冲销任务，备件货*/
    @Override
    public ResponseResult generateWithDrawTaskX(String werks, String whsLocationCode, String userId, String createDate, String relatedTaskId, String sapVoucherNumber, SapDeliveryNote sapDeliveryNote, List<?> shelfOnTaskDtls, String pdaSn,String mobileType) {
        WithdrawTask withdrawTask = newWithdrawTask(werks, whsLocationCode, "X", createDate, relatedTaskId, sapVoucherNumber, sapDeliveryNote.getDeliveryNoteSap(), mobileType, userId, pdaSn);
        int res = withdrawTaskMapper.insert(withdrawTask);
        if (res <= 0) {
            return ResponseResult.error("Error when create withdraw Task");
        }
        return iWithdrawTaskDtlService.generateWithdrawTaskDtlX(withdrawTask.getUuid(), sapDeliveryNote.getDeliveryNoteSap(), shelfOnTaskDtls);

    }

    /* 生成入库冲销任务，贸易货*/
    @Override
    public ResponseResult generateWithDrawTaskM(String werks, String whsLocationCode, String userId, String createDate, String relatedTaskId, String sapVoucherNumber, SapDeliveryNote sapDeliveryNote, List<?> storageList, String pdaSn,String mobileType) {
        WithdrawTask withdrawTask = newWithdrawTask(werks, whsLocationCode, "M", createDate, relatedTaskId, sapVoucherNumber, sapDeliveryNote.getDeliveryNoteSap(), mobileType, userId, pdaSn);
        int res = withdrawTaskMapper.insert(withdrawTask);
        if (res <= 0) {
            return ResponseResult.error("Error when create withdraw Task");
        }
        return iWithdrawTaskDtlService.generateWithdrawTaskDtlM(withdrawTask.getUuid(), sapDeliveryNote.getDeliveryNoteSap(), storageList);
    }

    WithdrawTask newWithdrawTask(String werks, String whsLocationCode, String setTaskCategory, String createDate, String relatedTaskId, String sapVoucherNumber, String deliveryNoteSap, String mobileType, String userId, String pdaSn) {
        WithdrawTask withdrawTask = new WithdrawTask();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        withdrawTask.setUuid(uuid);
        withdrawTask.setCreateDate(createDate);
        withdrawTask.setDeliveryNoteSap(deliveryNoteSap);
        withdrawTask.setRelatedTaskId(relatedTaskId);
        withdrawTask.setSapVoucherNumber(sapVoucherNumber);
        // X 备件货，M 贸易货
        withdrawTask.setTaskCategory(setTaskCategory);
        // 1入库冲销；2出库冲销；
        withdrawTask.setMobileType(mobileType);
        withdrawTask.setTaskStatus("1");
        withdrawTask.setWerks(werks);
        withdrawTask.setWhsLocationCode(whsLocationCode);
        withdrawTask.setCreateUserid(userId);
        withdrawTask.setPdaSn(pdaSn);
        return withdrawTask;
    }

    /*按条件查询冲销历史记录*/

    @Override
    public ResponseResult getWithdrawTasks(String userId, String deliveryNoteSap, String mobileType, String taskCategory, String relatedTaskId) {
        userId = StringUtils.isEmpty(userId) ? null : userId;
        deliveryNoteSap = StringUtils.isEmpty(deliveryNoteSap) ? null : deliveryNoteSap;
        mobileType = StringUtils.isEmpty(mobileType) ? null : mobileType;
        taskCategory = StringUtils.isEmpty(taskCategory) ? null : taskCategory;
        relatedTaskId = StringUtils.isEmpty(relatedTaskId) ? null : relatedTaskId;
        return ResponseResult.success().add("withdrawTasks", withdrawTaskMapper.getWithdrawTasks(userId, deliveryNoteSap, mobileType, taskCategory, relatedTaskId));
    }

    // 获取withdraw的详情数据
    @Override
    public ResponseResult getwithdrawTaskDtl(String uuid) {
        WithdrawTask withdrawTask = withdrawTaskMapper.selectOne(new QueryWrapper<WithdrawTask>().eq("UUID", uuid));
        if (null == withdrawTask) {
            return ResponseResult.error("can not load Withdraw task for uuid:" + uuid);
        }
        List<WithdrawTaskDtl> withdrawTaskDtls = withdrawTaskDtlMapper.selectList(new QueryWrapper<WithdrawTaskDtl>().eq("UUID", uuid));
        if (null == withdrawTaskDtls) {
            return ResponseResult.error("can not load Withdraw task Dtls for uuid:" + uuid);
        }

        return ResponseResult.success().add("withdrawTask", withdrawTask).add("withdrawTaskDtls", withdrawTaskDtls);
    }
}
